/*
 * {} _actionPaste
 *
 * Activates the paste dialog.
 * 
 * Parameters:
 * context	- {ChatManager} The PCDM chat manager class.
 */
function _actionPaste(context) {
    $.ajax({
        type: 'GET',
        url: "paster/popup",
        success: function(responseData, textStatus, xhr) {
            $.modal(responseData, {
                overlayClose: true,
                onShow: function(dialog) {
                    // Hook into paste submit button
                    $("#pcdm_pasteSubmit").click(function(){
                        _actionPasteSubmit(context);
                    });
                }
            });            	
        }
    });
}

/*
 * {} _actionPasteSubmit
 *
 * Submits the paste form and handles any response from the server.
 * 
 * Parameters:
 * context	- {ChatManager} The PCDM chat manager class.
 */
function _actionPasteSubmit(context, form) {
    $.ajax({
        type: 'POST',
        url: "paster/create",
        data: $("#pcdm_formPaste").serialize(),
        success: function(responseData, textStatus, xhr) {
            if(responseData["errors"].length > 0) {
                context._handleChatError($("#pasteError"), responseData["errors"], 10000);
            }
            else {
                var jqChatContainer = $("#"+context._currentChannelKey);
                jqChatContainer.append("<div class='actionInformation'>Your paste has been created: [<a target='_blank' href='paster/"+responseData["data"][0].pk+"'>Public Link</a>] [<a target='_blank' href='paster/edit/"+responseData["data"][0].pk+"/"+responseData["data"][0].fields.edit_hash+"'>Edit Link</a>]</div>");
                jqChatContainer.attr({scrollTop: jqChatContainer.attr("scrollHeight") - jqChatContainer.height()});
                
                var jqStatusPane = $("#pcdm_paneStatus");
                jqStatusPane.append("<div class='actionInformation'><span class='actionTimestamp'>"+(new Date()).toLocaleTimeString()+"</span>Your paste has been created: [<a target='_blank' href='paster/"+responseData["data"][0].pk+"'>Public Link</a>] [<a target='_blank' href='paster/edit/"+responseData["data"][0].pk+"/"+responseData["data"][0].fields.edit_hash+"'>Edit Link</a>]</div>");
                jqStatusPane.attr({scrollTop: jqStatusPane.attr("scrollHeight") - jqStatusPane.height()});

                $.modal.close();
                $("#pcdm_formPaste").each(function(){
                    this.reset();
                });
            }
        },
        error: function(xhr, textStatus, errorThrown) {
            context._handleChatError($("#pasteError"), ["Unable to create paste."], 10000);
        },
        dataType: "json"
    });
}

function handlePaste(context, data) {
  _actionPaste(context);
}

if(typeof chatManager != "undefined") {
	chatManager.insertActionModule("paste", handlePaste);	
}
